var token;
var u_id;
var num;
var key

var ProctorList_size;

var wsUrl = "ws://localhost:7023"

//接收多值的js函数
function manyValues() {
    var url = window.location.search;
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        key = [token, u_id, num];
        var value = new Array(strs.length);
        for (i = 0; i < strs.length; i++) {
            value[i] = unescape(strs[i].split("=")[1]);
            key[i] = value[i];
        }
    }
}

//接收Login.html传过来的值
manyValues();
token = key[0];
u_id = key[1];
num = key[2];

listProctorExams();

//与服务器建立ws连接
wsTeacherLogin();

function wsTeacherLogin() {
    var ws = new WebSocket(wsUrl + "/server/TeacherLoginServer/" + num);

    ws.onopen = function (evt) {
        // window.alert("成功与服务端建立websocket连接...")
    }

    //接受消息
    ws.onmessage = function (evt) {
        window.alert(evt.data);
        //接收到开始考试的信息后刷新页面，重新加载开始信息
        window.location.reload();
    }

    //断开连接
    ws.onclose = function () {
        $("#username").html("<h3 style=\"text-align: center;\">用户：" + username + "<span>-离线</span></h3>");
    }

}

//查询考试情况
function listProctorExams() {
    $.ajax({
        headers: {
            'Authorization': token,
        },
        type: "GET",
        url: "/api/examination/listExamByInvigilatorId?invigilatorId=" + u_id,
        async: false,
        success: function (result) {
            var txt = "";
            var list = result.data;
            ProctorList_size = list.length;
            for (var i = 0; i < list.length; i++) {
                var txt2 = '<div style="background: aquamarine;width: 500px">\n' +
                    '    <p id="examId" style="display: none">' + list[i].examId + '</p>\n' +
                    '    <p class="examName">考试名称：' + list[i].examName + '</p>\n' +
                    '    <p id="startTime">开始时间：' + list[i].startTime + '</p>\n' +
                    '    <p id="endTime">时长：' + list[i].duration + 'min' + '</p>\n' +
                    '    <p id="statusName">考试状态：' + list[i].statusName + '</p>\n' +
                    '    <p class="status" style="display: none">' + list[i].status + '</p>\n' +
                    '    <span>注意：请提前10~15min准备开始以提醒学生!</span>\n' +
                    '    <p ><button class="btn-beginExam" value=' + list[i].examId + '>开始考试</button></p>\n' +
                    '    <p ><button class="btn-delayExam" value=' + list[i].examId + '>延长考试</button></p>\n' +
                    '    <p ><button class="btn-mark" value=' + list[i].examId + '>批改</button></p>\n' +
                    '</div>'
                txt += txt2;
            }
            $("#div-proctorExamList").html(txt);
        }
    });
}

//开始考试
for (let i = 0; i < ProctorList_size; i++) {
    $($(".btn-beginExam")[i]).click(function () {
        var status = $($(".status")[i]).html();
        if (status == 1 || status == 2 || status == 3) {
            alert("不能开始该考试！");
            return;
        }
        examId = $(".btn-beginExam")[i].value;
        var per_time = prompt("准备时间：");
        var thisExamName = $($(".examName")[i]).html()
        alert(thisExamName)
        $.ajax({
            headers: {
                'Authorization': token,
            },
            contentType: 'application/json; charset=utf-8',
            type: "POST",
            url: "/api/examination/beginExam",
            data: JSON.stringify({
                "examId": examId,
                "perTime": per_time
            }),
            async: false,
            success: function (result) {
                if (result.success) {
                    var msg = thisExamName + "，将于" + per_time + "分钟后考试，请做好准备！"
                    $.ajax({
                        headers: {
                            'Authorization': token,
                        },
                        url: "/api/publisher/sendBeginExamMessage/" + msg + "/" + result.data.toString() + "/" + examId,
                        async: false,
                        success: function (result) {
                            alert(result.message);
                            window.location.reload();
                        }
                    })
                } else {
                    alert(result.message)
                }
            }
        });
    });
}

//延长考试
for (let i = 0; i < ProctorList_size; i++) {
    $($(".btn-delayExam")[i]).click(function () {
        var theExamId = $(".btn-beginExam")[i].value;
        var status = $($(".status")[i]).html();
        //只有正在进行中的考试才能延长时间
        if (status == 2) {
            var delay_time = prompt("延长时间：");
            var thisExamName2 = $($(".examName")[i]).html()
            alert(thisExamName2)
            $.ajax({
                headers: {
                    'Authorization': token,
                },
                contentType: 'application/json; charset=utf-8',
                type: "POST",
                url: "/api/publisher/delayExam/" + theExamId + "/" + delay_time,
                async: false,
                success: function (result) {
                    if (result.success) {
                        alert(result.message)
                        window.location.reload();
                    } else {
                        alert(result.message)
                    }
                }
            });
        } else {
            alert("该考试不在进行状态，无法延长时间！");
            return;
        }

    });
}

for (let i = 0; i < ProctorList_size; i++) {
    $($(".btn-mark")[i]).click(function () {
        let examId = $(".btn-mark")[i].value;
        let status = $($(".status")[i]).html();
        //只有正在进行中的考试才能评分
        if (status == 3) {
            window.location.href = '/api/templates/Mark.html?token=' + token + "&u_id=" + u_id + "&num=" + num + "&examId=" + examId
        } else {
            alert("该考试尚未结束，不能进行评分！");
            return;
        }

    });
}
